package cn.schoolwow.quickapi.module.business.apiParameter.flow.parameter;

import cn.schoolwow.quickapi.module.business.api.domain.API;
import cn.schoolwow.quickapi.module.business.apiParameter.domain.APIParameter;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestParam;

import java.lang.reflect.Parameter;

public class GetByRequestParamAnnotationFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        API api = (API) flowContext.checkData("api");
        Parameter parameter = (Parameter) flowContext.checkData("parameter");
        APIParameter apiParameter = (APIParameter) flowContext.checkData("apiParameter");
        StringBuilder queryBuilder = (StringBuilder) flowContext.checkData("queryBuilder");
        StringBuilder requestBodyBuilder = (StringBuilder) flowContext.checkData("requestBodyBuilder");

        RequestParam requestParam = parameter.getAnnotation(RequestParam.class);
        if(null==requestParam){
            return;
        }
        String value = requestParam.name();
        if(StringUtils.isBlank(value)){
            value = requestParam.value();
        }
        if(StringUtils.isBlank(value)){
            value = requestParam.value();
        }
        if(StringUtils.isBlank(value)){
            value = apiParameter.name;
        }

        api.contentType = "application/x-www-form-urlencoded";
        if("POST".equalsIgnoreCase(api.requestMethod)
                ||"PUT".equalsIgnoreCase(api.requestMethod)
                ||"PATCH".equalsIgnoreCase(api.requestMethod)
        ){
            requestBodyBuilder.append(value+"={"+value+"}&");
        }else{
            queryBuilder.append(value+"={"+value+"}&");
        }
        apiParameter.required = requestParam.required();

        flowContext.brokenCurrentCompositeBusiness("");
    }

    @Override
    public String name() {
        return "通过RequestParam注解获取参数";
    }
}
